<?php
namespace  app\manage\model;
use think\Db;
use think\Model;
class UserRole extends Model{
    protected  $table = 'user_role';

    /**
     * @param $data
     * @return int|string
     */
    public function m_insert($data) {
        $data = Db::name($this->table)
            ->insert($data);
        return Db::name($this->table)->getLastInsID();
    }

    /**
     * 编辑
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function m_update($action_id, $data) {
        $data = Db::name($this->table)
            ->where(['user_id'=>$action_id])
            ->update($data);
        return $data;
    }

    /**
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function m_delete($action_id) {
        $data = Db::name($this->table)
            ->where(['id'=>$action_id])
            ->delete();
        return $data;
    }

    /**
     * @param $action_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($action_id) {
        $data = Db::name($this->table)
            ->where(['id'=>$action_id])
            ->field('id,user_id,role_id')
            ->find();
        return $data;
    }

    /**
     * @param $admin_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRoleRelation($admin_id) {
        $data = Db::name($this->table)
            ->where(['user_id'=>$admin_id])
            ->field('user_id, role_id')
            ->select();
        return $data;
    }

    /**
     * @param $role_id
     * @param $action_id
     * @return int|string
     */
    public function setRoleRelation($user_id, $role_id) {
        $data['role_id'] = $role_id;
        $data['user_id'] = $user_id;
        return $this->m_insert($data);
    }

    /**
     * @param $role_id
     * @param $action_id
     * @return int|string
     */
    public function updateActionRelation($user_id, $role_id) {
        $data['role_id'] = $role_id;
        return $this->m_update($user_id, $data);
    }
    /**
     * 获取用户 create_id
     */
    public function create_id($user_id) {
        $data = Db::name('admin_user')
            ->where(['admin_id'=>$user_id])
            ->field('admin_id,create_id')
            ->find();
        if($data['create_id']==0){
            return $data['admin_id'];
        }
        if($data['create_id']==1){
            return $data['admin_id'];
        }else{
            return $data['create_id'];
        }
    }
}